package part2.task3;

import java.util.LinkedList;
import java.util.List;

public class ConnectionMonitor extends Thread {
    private static final int IDLE_TIMEOUT = 1000;
    private List<ControlledConnection> connections = new LinkedList<ControlledConnection>();
    private ConnectionPool pool;

    public ConnectionMonitor(ConnectionPool pool) {
        setDaemon(true);
        this.pool = pool;
    }

    public void addConnection(ControlledConnection connection) {
        synchronized (connections) {
            connections.add(connection);
        }
    }

    public void removeConnection(ControlledConnection connection) {
        synchronized (connections) {
            connections.remove(connection);
        }
    }

    @Override
    public void run() {
        while (true) {
            long currentTime = System.currentTimeMillis();
            List<ControlledConnection> unUsedConnections = new LinkedList<ControlledConnection>();
            synchronized (connections) {
                for (ControlledConnection connection : connections)
                    if (currentTime - connection.getTime() > IDLE_TIMEOUT && !connection.isUsed())
                        unUsedConnections.add(connection);
            }

            for (ControlledConnection connection : unUsedConnections)
                pool.checkIn(connection);

            try {
                Thread.sleep(IDLE_TIMEOUT);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
